﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace Awaken.Utils.WidgetCode
{
    public static class StringExtensions
    {
        public static char DirSeparatorChar = '\\';

		public static char SpaceSeparatorChar = ' ';

		public static string SpaceSeparator = " ";

		/// <summary>
		/// 字符串重复渲染
		/// </summary>
		/// <param name="str"></param>
		/// <param name="n"></param>
		/// <returns></returns>
		public static string RepeatString(this string str, int n)
        {
            if (n <= 0) return string.Empty;

            char[] arr = str.ToCharArray();

            char[] arrDest = new char[arr.Length * n];

            for (int i = 0; i < n; i++)
            {
                Buffer.BlockCopy(arr, 0, arrDest, i * arr.Length * 2, arr.Length * 2);
            }

            return new string(arrDest);
        }

        /// <summary>
        /// 汉字转换拼音
        /// </summary>
        /// <param name="chinese"></param>
        /// <returns></returns>
        public static string ConvertPinyin(this string chinese)
        {
            throw new NotImplementedException();
            if (string.IsNullOrWhiteSpace(chinese)) return string.Empty;

            string pinyin = string.Empty;

            foreach (char c in chinese)
            {
                try
                {
                    //TODO:
                    //ChineseChar chineseChar = new ChineseChar(c);
                    //string first = chineseChar.Pinyins[0];//汉字是有多音字的 取第一个
                    //pinyin += first.Substring(0, first.Length - 1);
                }
                catch
                {
                    pinyin += c.ToString();
                }
            }

            return pinyin;
        }

        /// <summary>
        /// 过滤空字符串
        /// </summary>
        /// <param name="seeds"></param>
        /// <returns></returns>
        public static string[] FilterEmpty(this string[] seeds)
        {
            if (seeds == null || !seeds.Any()) return new string[] { };

            return (from seed in seeds
                    where !string.IsNullOrWhiteSpace(seed)
                    select seed.Trim()).ToArray();
        }

        /// <summary>
        /// 字符串中间部分打包加密
        /// </summary>
        /// <param name="words"></param>
        /// <param name="prefixLen"></param>
        /// <param name="afterLen"></param>
        /// <returns></returns>
        public static string EncryptPacking(this string words, int prefixLen, int afterLen)
        {
            if (string.IsNullOrWhiteSpace(words)) return string.Empty;

            words = words.Trim();

            var length = words.Length;

            if (length < prefixLen + afterLen)
            {
                return "**" + words;
            }

            var pad = string.Empty.PadLeft(length - (prefixLen + afterLen), '*');

            return words.Substring(0, prefixLen) + pad + words.Substring(length - afterLen, afterLen);
        }

        /// <summary>
        /// 判断字符串是否包含数字
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static bool IsContainsNumber(this string str)
        {
            if (string.IsNullOrEmpty(str)) return false;
            return Regex.IsMatch(str, @"\d+");
        }

        /// <summary>
        /// 字符串->可空时间类型
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static DateTime? ToDateTimeNullable(this string str)
        {
            DateTime dt = new DateTime();
            if (DateTime.TryParse(str, out dt))
                return dt;
            return null;
        }

        /// <summary>
        /// 手机号码中间加上横线
        /// </summary>
        /// <param name="pNumber"></param>
        /// <returns></returns>
        public static string AddPhoneMiddleLine(this string pNumber)
        {
            if (!string.IsNullOrEmpty(pNumber) && pNumber.Length == 11)
                return pNumber.Insert(3, "-").Insert(8, "-");
            return string.Empty;
        }

        /// <summary>
        /// 字符串中查找参数
        /// </summary>
        /// <param name="paramName"></param>
        /// <param name="paramsStr"></param>
        /// <returns></returns>
        public static string GetParams(this string paramsStr, string paramName)
        {
            Regex regParam = new Regex("(?:^|&)" + paramName + "=(?<Value>[^&]*)", RegexOptions.IgnoreCase);
            Match mth = regParam.Match(paramsStr.Trim());
            if (mth.Success)
            {
                //匹配成功
                return mth.Groups["Value"].Value;
            }
            else { return null; }
        }

		/// <summary>
		/// 生成指定长度的随机数
		/// </summary>
		/// <param name="length"></param>
		/// <returns></returns>
		public static string GetRandomNumber(int length)
		{
			const int maxNumber = 10;

			string container = string.Empty;

			for (int i = length - 1; i >= 0; i--)
			{
				Random random = RandomBuilder.BuildRandom();

				container += random.Next(maxNumber).ToString();
			}
			
			return container;


		}        

        /// <summary>
        /// 获取四位随机数（不重复、逗号分割）
        /// </summary>
        /// <param name="count"></param>
        /// <returns></returns>
        public static string Get4Number(int count)
        {
            List<int> MyArray = new List<int>();
            Random random = new Random();
            string str = null;


            //循环的次数     
            int Nums = 4;
            while (Nums > 0)
            {
                int i = random.Next(0, count);
                if (MyArray.Count < 4 && !MyArray.Contains(i))
                {
                    MyArray.Add(i);
                }
                else
                    continue;
                Nums -= 1;
            }
            for (int j = 0; j <= MyArray.Count - 1; j++)
            {
                str += MyArray[j].ToString() + ",";
            }
            //----------------------- 随机密码结束 ---------------------------   
            return str.Trim(',');
        }
    }
}
